<template>
  <el-card class="card_box card_header_top">
    <template #header>
      <div class="header_wrapper">
        <div class="header_nav">
          <span style="font-size: 13px;color: #999999;">数据概览</span>
          <span style="font-size: 14px;font-weight: bold;color: #333333;">/信息录入</span>
        </div>
        <div class="header_tabs">
          <el-radio-group v-model="listForm.data.radioType" @change="resetPagination">
            <el-radio-button :label="1">美团CDK</el-radio-button>
            <el-radio-button :label="2">饿了么联名卡</el-radio-button>
          </el-radio-group>
        </div>
      </div>
    </template>
    <el-form ref="formRef" :model="form.data" :rules="rules" inline :hide-required-asterisk="true">
      <el-row justify="space-between">
        <el-col :span="30">
          <el-form-item label="时间" prop="date">
            <el-date-picker
                v-model="form.data.date"
                type="month"
                :editable="false"
                value-format="YYYY-MM"
                placeholder="选择时间"
                :class="form.data.date ? 'date_prefix_show':'date_prefix_close'"
                style="width: 255px !important;"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="本月累计金额" prop="cumulativeAmount">
            <el-input v-model="form.data.cumulativeAmount" clearable placeholder="请输入金额"
                      style="width: 255px !important">
              <template #suffix>
                <span style="color: #333333">元</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="初始金额" prop="initialAmount">
            <el-input
                v-model="form.data.initialAmount"
                clearable
                placeholder="请输入金额"
                style="width: 255px !important"
            >
              <template #suffix>
                <span style="color: #333333">元</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="confirmTheEntry(formRef)" class="button_style">确定录入</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
  <!-- 表格主体 -->
  <el-card>
    <template #header>
      <div class="card_header">
        <span class="card_title">列表展示</span>
        <div class="table_invoicedAmount">
          <span>当前累计金额：</span>
          <span>{{ formatNumber(26326) }}</span>
        </div>
      </div>
    </template>
    <div class="global_table_wrapper">
      <el-table
          :data="dataList.data"
          highlight-current-row
          stripe
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f8f8f9' }"
          border
          max-height="500"
      >
        <el-table-column type="index" label="序号" min-width="70"/>
        <el-table-column prop="date" label="日期" min-width="280" :show-overflow-tooltip="true"/>
        <el-table-column prop="amount" label="金额" min-width="280" :show-overflow-tooltip="true"/>
        <el-table-column prop="operator" label="制作人" min-width="280" :show-overflow-tooltip="true"/>
        <el-table-column prop="operationTime" label="制作时间" min-width="280" :show-overflow-tooltip="true"/>
        <el-table-column fixed="right" label="操作" min-width="250">
          <template #default="scope">
            <el-button type="primary" link size="small" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button type="primary" link size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <Pagination
            :total="listForm.data.total"
            v-model:page="listForm.data.pageNo"
            v-model:limit="listForm.data.pageSize"
            @pagination="initialize"
        />
      </div>
    </div>
  </el-card>
  <!--  修改信息录入-->
  <Dialog v-model="modifyInfoVisible" title="修改信息" width="30%" submit-text="提交" :close-text-visible="false"
          submit-button-width="160"
          @clear-form="clearModifyForm(modifyFormRef)" @submit-form="submitModifyForm(modifyFormRef)">
    <el-form :model="modifyForm.data" ref="modifyFormRef" :rules="modifyRules" :hide-required-asterisk="true">
      <el-row justify="center">
        <el-col :span="18" :push="1">
          <el-form-item label="时间" prop="date">
            <el-date-picker
                v-model="modifyForm.data.date"
                type="month"
                :editable="false"
                value-format="YYYY-MM"
                placeholder="选择时间"
                :class="modifyForm.data.date ? 'date_prefix_show':'date_prefix_close'"
                style="width: 255px !important;"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="18" :push="1">
          <el-form-item label="金额" prop="amount">
            <el-input
                v-model="modifyForm.data.amount"
                clearable
                placeholder="请输入金额"
                style="width: 255px !important"
            >
              <template #suffix>
                <span style="color: #333333">元</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </Dialog>
</template>
<script setup lang="ts">
import Dialog from '@/components/Dialog/index.vue'
import {formatNumber} from "@/utils/wheel";
import Pagination from "@/components/Pagination/index.vue";
import {ElMessageBox, ElMessage} from 'element-plus'
import type {FormInstance} from 'element-plus'

const route = useRoute()
const formRef = ref();
const modifyFormRef = ref();

let modifyInfoVisible = ref(false)

let form = reactive<{ data: Record<string, any> }>({
  data: {
    date: '',
    cumulativeAmount: '',
    initialAmount: '',
  }
});
let modifyForm = reactive<{ data: Record<string, any> }>({
  data: {
    date: '',
    amount: '',
  }
});
const listForm = reactive<{ data: Record<string, any> }>({
  data: {
    radioType: 1,
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
})
const dataList = reactive<{ data: Record<string, any> }>({
  data: []
});
const rules = reactive({
  date: [{
    required: true, message: '请选择时间', trigger: 'change'
  }],
  cumulativeAmount: [{
    required: true, validator: (rule: any, value: any, callback: any) => {
      if (value) {
        const decimalFraction = /^[0-9]+(\.[0-9]{1,2})?$/
        const positiveInteger = /^[1-9][0-9]*$/
        if (decimalFraction.test(value) || positiveInteger.test(value)) {
          if (value < 0.01) {
            callback(new Error('输入金额必须大于0.01'))
          } else {
            callback()
          }
        } else {
          callback(new Error('金额应为整数或小数（小数点后最多两位小数）'))
        }
      } else {
        callback(new Error('请输入本月累计金额'))
      }
    }, trigger: ['blur']
  }],
  initialAmount: [{
    required: true, validator: (rule: any, value: any, callback: any) => {
      if (value) {
        const decimalFraction = /^[0-9]+(\.[0-9]{1,2})?$/
        const positiveInteger = /^[1-9][0-9]*$/
        if (decimalFraction.test(value) || positiveInteger.test(value)) {
          if (value < 0.01) {
            callback(new Error('输入金额必须大于0.01'))
          } else {
            callback()
          }
        } else {
          callback(new Error('金额应为整数或小数（小数点后最多两位小数）'))
        }
      } else {
        callback(new Error('请输入初始金额'))
      }
    }, trigger: ['blur']
  }],
})

const modifyRules = reactive({
  date: [{
    required: true, message: '请选择时间', trigger: 'change'
  }],
  amount: [{
    required: true, validator: (rule: any, value: any, callback: any) => {
      if (value) {
        const decimalFraction = /^[0-9]+(\.[0-9]{1,2})?$/
        const positiveInteger = /^[1-9][0-9]*$/
        if (decimalFraction.test(value) || positiveInteger.test(value)) {
          if (value < 0.01) {
            callback(new Error('输入金额必须大于0.01'))
          } else {
            callback()
          }
        } else {
          callback(new Error('金额应为整数或小数（小数点后最多两位小数）'))
        }
      } else {
        callback(new Error('请输入金额'))
      }
    }, trigger: ['blur']
  }],
})
const confirmTheEntry = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
          '确定录入信息吗?',
          '温馨提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
      )
          .then(async () => {
            // const resp = await baseRequest.post('', form.data) as any
            // if (resp.code == 0) {
            //   ElMessage({
            //     type: 'success',
            //     message: '录入信息成功',
            //   })
            //   resetPagination()
            // }
            ElMessage({
              type: 'success',
              message: '录入信息成功',
            })
            resetPagination()
          })
          .catch(() => {
          })
    }
  })
}
const handleEdit = (row: Record<string, any>) => {
  modifyForm.data.date = row.date
  modifyForm.data.amount = row.amount
  modifyInfoVisible.value = true
}
const handleDelete = (row: Record<string, any>) => {
  ElMessageBox.confirm(
      '确定要删除此条信息吗？删除后不可恢复。',
      '温馨提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        // const resp = await baseRequest.post('', {id: row.id}) as any
        // if (resp.code == 0) {
        //   ElMessage({
        //     type: 'success',
        //     message: '删除成功',
        //   })
        //   resetPagination()
        // }
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        resetPagination()
      })
      .catch(() => {
      })
}
//修改信息提交
const submitModifyForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      // const resp = await baseRequest.post('', modifyForm.data) as any
      // if (resp.code == 0) {
      //   ElMessage({
      //     type: 'success',
      //     message: '修改信息成功',
      //   })
      //   resetPagination()
      //   modifyInfoVisible.value = false
      // }
      ElMessage({
        type: 'success',
        message: '修改信息成功',
      })
      resetPagination()
      modifyInfoVisible.value = false
    }
  })
}
//重置修改信息表单
const clearModifyForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  modifyForm.data = {
    date: '',
    amount: '',
  }
  formEl.resetFields()
}
//重置录入信息表单
const clearForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  modifyForm.data = {
    date: '',
    cumulativeAmount: '',
    initialAmount: '',
  }
  formEl.resetFields()
}
const resetPagination = () => {
  listForm.data.pageNo = 1
  listForm.data.pageSize = 10
  listForm.data.total = 0
  initialize()
}
const initialize = async () => {
  clearForm(formRef.value)
  const formData = JSON.parse(JSON.stringify(listForm.data))
  console.log(formData)
  // const resp = await baseRequest.get('/userOrder/dataOverview', formData) as any
  // console.log(resp)
  // dataList.data = resp.data.list
  // form.data.total = resp.data.total
  dataList.data = [
    {
      id: 1,
      date: '2022-06-12 00:00:00',
      amount: 5656,
      operator: 'hua',
      operationTime: '2022-06-12 00:00:00',
    },
    {
      id: 2,
      date: '2022-06-12 00:00:01',
      amount: 565,
      operator: 'hua',
      operationTime: '2022-06-12 00:00:00',
    },
  ] as any;
  listForm.data.total = 50;
};
onMounted(() => {
  initialize();
});
</script>
<style lang="scss" scoped>
.card_header_top {
  :deep(.el-card__header) {
    padding: 20px 0 0 20px !important;
  }
}

:deep(.button_style) {
  border-color: var(--el-color-primary) !important;
  color: var(--el-color-primary) !important;
}

:deep(.date_prefix_show .el-input__prefix) {
  display: none;
  position: absolute !important;
  right: 15px !important;
  color: #333333 !important;
}

:deep(.date_prefix_close .el-input__prefix) {
  position: absolute !important;
  right: 5px !important;
  color: #333333 !important;
}

.header_wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;

  .header_nav {
    margin-bottom: 5px;
  }

  .header_tabs {
    margin-right: 30px;
  }
}

.card_title {
  font-size: 16px;
  color: #333333;
  font-weight: bold;
}

.table_invoicedAmount {
  margin-right: 10px;
  font-size: 16px;

  & span:nth-of-type(2) {
    font-size: 20px;
    font-weight: bold;
  }
}
</style>

